import React, { useState, useEffect, useCallback } from 'react';
import { Button, Modal, Tree, Transfer, Spin } from 'antd';
import { flatTryCatch } from '../../../../servers/http';
import { industryIpaApi } from 'admin/servers/servers';
import VirtualListTransfer from './VirtualListTransfer';
import './index.scss';

interface Props {
  onPhoneFromChild: (data: string[]) => void;
}

const SelectIpa: React.FC<Props> = ({ onPhoneFromChild }) => {
  /** 弹窗显隐 */
  const [isModalVisible, setIsModalVisible] = useState(false);

  const handleTriggerModal = (flag: boolean) => {
    setIsModalVisible(flag);
  };

  const handleOk = () => {
    const phoneList = [];
    targetKeys.forEach(key => {
      const pitch = personData.find(({ id }) => key === id) ?? { phone: '' };
      phoneList.push(pitch.phone);
    });
    onPhoneFromChild(phoneList);
    handleTriggerModal(false);
  };

  /** 点树后，加载数据 */
  const [ipaLoading, setIpaLoading] = useState(false);

  /** 树数据 */
  const [treeData, setTreeData] = useState([
    { name: '全部', key: 'root', id: 'root', children: [] },
  ]);

  const fetchGroupTree = useCallback(async () => {
    const { response, error } = await flatTryCatch(industryIpaApi.readGroupTree());
    if (error) return;
    const rootNode = { name: '全部', key: 'root', id: 'root', children: [] };
    rootNode.children = response.data ?? [];
    setTreeData([rootNode]);
  }, []);

  useEffect(() => {
    fetchGroupTree();
  }, [fetchGroupTree]);

  /** 可选人数据 */
  const [personData, setPersonData] = useState([]);
  const handleSelectTree = async (selectedKeys: string[]) => {
    setIpaLoading(true);

    const pitchGroupId = selectedKeys[0] === 'root' ? undefined : selectedKeys[0];
    const {
      response: { data = {} },
      error,
    } = await flatTryCatch(industryIpaApi.readPerson({ groupId: pitchGroupId, doPage: false }));
    setIpaLoading(false);
    if (error) return;

    const tempList =
      data.list?.map(({ phone, id, name }) => ({
        key: id,
        id,
        phone,
        name,
        // ...item,
      })) ?? [];
    setPersonData(tempList);
  };

  /** 已选人数据 */
  const [targetKeys, setTargetKeys] = useState([]);
  const onChange = (nextTargetKeys: string[]) => {
    setTargetKeys(nextTargetKeys);
  };

  return (
    <div>
      <Button type="primary" onClick={() => handleTriggerModal(true)}>
        通讯录
      </Button>
      <Modal
        title="选择通讯录"
        width={1100}
        visible={isModalVisible}
        destroyOnClose
        onOk={handleOk}
        onCancel={() => handleTriggerModal(false)}
      >
        <Spin spinning={ipaLoading} tip="通讯录数据加载中，请稍后">
          <div className="ipa-container">
            <div className="ipa-left">
              <Tree
                defaultExpandedKeys={['root']}
                fieldNames={{ title: 'name', key: 'id', children: 'children' }}
                onSelect={handleSelectTree}
                treeData={treeData}
              />
            </div>
            <div className="ipa-right">
              {/* <Transfer
                dataSource={personData}
                titles={['待选', '已选']}
                operations={['添加', '删除']}
                showSelectAll
                showSearch
                targetKeys={targetKeys}
                onChange={onChange}
                render={item => item.name}
              /> */}
              <VirtualListTransfer
                dataSource={personData}
                titles={['待选', '已选']}
                operations={['添加', '删除']}
                showSelectAll
                showSearch
                targetKeys={targetKeys}
                onChange={onChange}
                render={item => item.name}
              />
            </div>
          </div>
        </Spin>
      </Modal>
    </div>
  );
};

export default SelectIpa;
